<?php
defined('_JEXEC') or die;

/**
 * Manager language helper class.
 *
 * @author	NhanLT
 */
class ManagerHelper { 
	
	const SERIAL_STATUS_NOT_USE = 0;
	const SERIAL_STATUS_USED = 1; 
	const SERIAL_STATUS_NOT_USE_TEXT = 'Can Use';
	const SERIAL_STATUS_USED_TEXT = 'Used';
    const SERIAL_BELONG_POND = 'pond';
    const SERIAL_BELONG_AGENCY = 'agency';
    const SERIAL_TYPE_RAW = 0;
    const SERIAL_TYPE_READY = 1;
    const SERIAL_TYPE_OPEN = 2;
    public static $SERIAL_TYPE = array(
        0 => 'raw',
        1 => 'ready',
        2 => 'open'
    );
	
	const CUSTOMER_TYPE_PERSONAL = 0;
	const CUSTOMER_TYPE_AGENCY = 1;
	const CUSTOMER_TYPE_PERSONAL_TEXT = 'Personal';
	const CUSTOMER_TYPE_AGENCY_TEXT = 'Agency';
	
	const PRODUCT_STATUS_CAN_USE = 0;
	const PRODUCT_STATUS_USED = 1;
	const PRODUCT_STATUS_EXPIRED = 2;
	const PRODUCT_STATUS_CAN_USE_TEXT = 'Can Use';
	const PRODUCT_STATUS_USED_TEXT = 'Used';
	const PRODUCT_STATUS_EXPIRED_TEXT = 'Expried';
	
	const FOLDER_UPLOAD = '/images/pim/';
	
	const ROLE_ADMIN = 9;
	const ROLE_REPORTER = 10;
	const ROLE_AGENCY = 11;
	
	const ROLE_ADMIN_TEXT = 'Admin';
	const ROLE_REPORTER_TEXT = 'Reporter';
	const ROLE_AGENCY_TEXT = 'Agency';
		
	const SELECT_POND = '- Select Pond -';
	const SELECT_CUSTOMER = '- Select Customer -';
	const SELECT_FISH_CLASS = '- Select Fish Class -';
	const SELECT_STATUS = '- Select Status -';
	const SELECT_TYPE = '- Select Type -';
	
	const ORDER_DIR = 'DESC';
	
	const ROW_START_EXPORT_EXCEL = 5;
	const ROW_START_IMPORT_EXCEL = 1;
	
	const NUM_OF_BATCH = 5;
    
    

	static function showMenuPim($c_active) {
		$com_Name  = "option=com_manager";
		$group_id = self::getGroupUser();
		
		switch ($group_id){
			case self::ROLE_AGENCY:
				JSubMenuHelper::addEntry(JText::_('Product Management'), "index.php?$com_Name&c=product", self::setMenuActive('product',$c_active));
				break;
			case self::ROLE_REPORTER:
				JSubMenuHelper::addEntry(JText::_('Serial Management'), "index.php?".$com_Name, self::setMenuActive('manager',$c_active));  
		        JSubMenuHelper::addEntry(JText::_('Product Management'), "index.php?$com_Name&c=product", self::setMenuActive('product',$c_active));
		        JSubMenuHelper::addEntry(JText::_('Pond Management'), "index.php?$com_Name&c=pond", self::setMenuActive('pond',$c_active));
		        JSubMenuHelper::addEntry(JText::_('Fish Class Management'), "index.php?$com_Name&c=fishclass", self::setMenuActive('fishclass',$c_active));  
		        JSubMenuHelper::addEntry(JText::_('Customer Management'), "index.php?$com_Name&c=customer", self::setMenuActive('customer',$c_active));
		        break;
		    default:
		    	JSubMenuHelper::addEntry(JText::_('Serial Management'), "index.php?".$com_Name, self::setMenuActive('manager',$c_active));  
		        JSubMenuHelper::addEntry(JText::_('Product Management'), "index.php?$com_Name&c=product", self::setMenuActive('product',$c_active));
		        JSubMenuHelper::addEntry(JText::_('Pond Management'), "index.php?$com_Name&c=pond", self::setMenuActive('pond',$c_active));
		        JSubMenuHelper::addEntry(JText::_('Fish Class Management'), "index.php?$com_Name&c=fishclass", self::setMenuActive('fishclass',$c_active));  
		        JSubMenuHelper::addEntry(JText::_('Customer Management'), "index.php?$com_Name&c=customer", self::setMenuActive('customer',$c_active));
			    JSubMenuHelper::addEntry(JText::_('Users Management'), "index.php?$com_Name&c=userpim", self::setMenuActive('userpim',$c_active));
			    JSubMenuHelper::addEntry(JText::_('Role'), "index.php?$com_Name&c=rolepim", self::setMenuActive('rolepim',$c_active));
			    JSubMenuHelper::addEntry(JText::_('Import'), "index.php?$com_Name&c=import", self::setMenuActive('import',$c_active));
			    JSubMenuHelper::addEntry(JText::_('Config Site'), "index.php?$com_Name&c=config", self::setMenuActive('config',$c_active));	
		}
	}
	
	static function setMenuActive($c, $menu_active) {
		if($c==$menu_active) return true;
		return false;
	}
	
	static function showToolBar($text, $showExport=false, $showManage=true) {
		$mainframe = JFactory::getApplication();
		$user =& JFactory::getUser();
		$array_groups = $user->groups;
		$group_id = self::getGroupUser();
		
		if($group_id > 0) {
			$Model = JModel::getInstance('Role', 'PimModel');
			$role_pim = $Model->getLoadObjByGroup(intval($group_id));
			
			if ($showExport) {
				if ($role_pim->report == 1) {
					JToolBarHelper::save('toExcel', "Export Excel");
					//JToolBarHelper::save('toWord', "Export Word");
					JToolBarHelper::save('toPDF', "Export PDF");
					if ($showManage) {
						JToolBarHelper::divider();
					}
				}
			}
			
			if ($showManage) {
				if($role_pim->add == 1){
					JToolBarHelper::addNew();
				}
				if($role_pim->edit == 1){
					JToolBarHelper::editList();
				}
				if($role_pim->delete == 1){
		        	JToolBarHelper::deleteList('Are you sure?', 'delete');
				}
			}
		} else {
			$Model = JModel::getInstance('Role', 'PimModel');
			$role_pim = $Model->getLoadObjByGroup(intval($group_id));
			
			if ($showExport) {
				JToolBarHelper::save('toExcel', "Export Excel");
				//JToolBarHelper::save('toWord', "Export Word");
				JToolBarHelper::save('toPDF', "Export PDF");
				if ($showManage) {
					JToolBarHelper::divider();
				}
			}
			
			if ($showManage) {
				JToolBarHelper::addNew();
				JToolBarHelper::editList();
		        JToolBarHelper::deleteList('Are you sure?', 'delete');
			}
		}
		
        JToolBarHelper::title( JText::_($text), 'searchtext.png' );
	}
	
	static function showToolBarForm($title) {
		JToolBarHelper::title($title, 'searchtext.png');
		JToolBarHelper::save();
		JToolBarHelper::cancel();
	}
	
 	static function getTextStatus($status_id=self::PRODUCT_STATUS_CAN_USE) {
		switch ($status_id) {
			case self::PRODUCT_STATUS_CAN_USE:
				return self::PRODUCT_STATUS_CAN_USE_TEXT;
			case self::PRODUCT_STATUS_USED:
				return self::PRODUCT_STATUS_USED_TEXT;
			case self::PRODUCT_STATUS_EXPIRED:
				return self::PRODUCT_STATUS_EXPIRED_TEXT;
		}
	}
	
	static function getTextStatusSerial($status_id=self::SERIAL_STATUS_NOT_USE) {
		switch ($status_id) {
			case self::SERIAL_STATUS_NOT_USE:
				return self::SERIAL_STATUS_NOT_USE_TEXT;
			case self::SERIAL_STATUS_USED:
				return self::SERIAL_STATUS_USED_TEXT;
		}
	}
	
	static function getTextTypeCustomer($type=self::CUSTOMER_TYPE_AGENCY) {
		switch ($type) {
			case self::CUSTOMER_TYPE_AGENCY:
				return self::CUSTOMER_TYPE_AGENCY_TEXT;
			case self::CUSTOMER_TYPE_PERSONAL:
				return self::CUSTOMER_TYPE_PERSONAL_TEXT;
		}
	}
		
	static function getListGroupUserPim() {
		$arr_status = array(
			array("id" => self::ROLE_ADMIN, 'name' => self::ROLE_ADMIN_TEXT),
			array("id" => self::ROLE_REPORTER, 'name' => self::ROLE_REPORTER_TEXT),
			array("id" => self::ROLE_AGENCY, 'name' => self::ROLE_AGENCY_TEXT)
		);
		return $arr_status;		
	}
	
	static function getListGroup() {
		$arr_status = array(
			self::ROLE_ADMIN=>self::ROLE_ADMIN_TEXT,
			self::ROLE_REPORTER_TEXT=>self::ROLE_REPORTER_TEXT,
			self::ROLE_AGENCY_TEXT=>self::ROLE_AGENCY_TEXT
		);
		return $arr_status;		
	}
	
	static function createNewUser($data = array()) {		 
		/* get the com_user params */
		jimport('joomla.application.component.helper'); // include libraries/application/component/helper.php
		$usersParams = &JComponentHelper::getParams( 'com_users' ); // load the Params
		 
		// "generate" a new JUser Object
		$user = JFactory::getUser(0); // it's important to set the "0" otherwise your admin user information will be loaded
		 
		if (!$user->bind($data)) { // now bind the data to the JUser Object, if it not works....
		    JError::raiseWarning('', JText::_( $user->getError())); // ...raise an Warning
		    return false; // if you're in a method/function return false
		}
		 
		if (!$user->save()) { // if the user is NOT saved...
		    JError::raiseWarning('', JText::_( $user->getError())); // ...raise an Warning
		    return false; // if you're in a method/function return false
		}
		 
		return $user; // else return the new JUser object
	}
	
	static function getGroupUser() {
		$mainframe = JFactory::getApplication();
		$user =& JFactory::getUser();
		$array_groups = $user->groups;
		
		if (isset($array_groups[self::ROLE_ADMIN])) {
			return $array_groups[self::ROLE_ADMIN];
		}
		if (isset($array_groups[self::ROLE_REPORTER])) {
			return $array_groups[self::ROLE_REPORTER];
		}
		if (isset($array_groups[self::ROLE_AGENCY])) {
			return $array_groups[self::ROLE_AGENCY];
		}
		return 0;
	}
	
	static function getRolePim() {
		$mainframe = JFactory::getApplication();
		$user =& JFactory::getUser();
		
		$group_id = self::getGroupUser();
		if ($group_id > 0) {
			$Model = JModel::getInstance('Role', 'PimModel');
			$role_pim = $Model->getLoadObjByGroup(intval($group_id));
			return $role_pim;
		} else {
			return -1;
		}
	}
	
	static function validateController($c) {
		$group_id = self::getGroupUser();
		
		if ($group_id == self::ROLE_AGENCY) {
			return 'product';
		}
		
		if ($group_id == self::ROLE_REPORTER) {
			if ($c == 'rolepim' || $c == 'config' || $c == 'userpim') {
				return 'manager';
			}
		}
		
		return $c;
	}
 
	static function validateRolePim($c='', $task='') {
		$objRole =  self::getRolePim();
		
		if ($objRole != -1) {
			switch ($task){
				case 'edit':
					return $objRole->edit; 
				case 'add':
					return $objRole->add; 
				case 'toExcel':
				case 'toWord':
				case 'toPDF':
					return $objRole->report; 
				case 'delete':
					return $objRole->delete; 
				default:
					return 1;
			}
		} else {
			return 1; 	
		}		
	}
	
	static function getAllPimConfig() {
		$model_config = JModel::getInstance('Config', 'ManagerModel');
		$arr_config = $model_config->getConfig();
		
		return $arr_config;
	}
	
	static function getExpiredDate($sale_date, $num_expired_value) {
        $interval = new DateInterval('P' . (int) $num_expired_value . 'D');
        $expired_date = date_format(date_add(new DateTime($sale_date), $interval), "Y-m-d H:i:s");
        
        return $expired_date;
	}

	static function formatDate($str_date) {
		return date('d-m-Y', strtotime($str_date));
	}
	
	static function getListCode($listObject) {
		$listCode = array();
		if (count($listObject) > 0) {
			foreach ($listObject as $code) {
				$listCode[] = $code->code;
			}
		}
		
		return $listCode;
	}

	static function formatPdf($model_name, $_header='', $_detail_header='') {
		$config = self::getAllPimConfig();
		
		$logo = !empty($config['logo'])?$config['logo']:PDF_HEADER_LOGO;
		$header = !empty($config['company_name'])?$config['company_name'].' - '.$config['address']:$_header;
		$detail_header = !empty($config['website'])?$config['website'].' - '.$config['email'].' - '.$config['phone'].' - '.$config['fax']:$_detail_header;
		
		// create new PDF document
		$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

		// set document information
		$pdf->SetCreator(PDF_CREATOR);
		
		// set default header data
		$pdf->SetHeaderData($logo, PDF_HEADER_LOGO_WIDTH, $header, $detail_header);
		
		// set header and footer fonts
		$pdf->setHeaderFont(Array('freesans', '', PDF_FONT_SIZE_MAIN));
		$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
		
		// set default monospaced font
		$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

		//set margins
		$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
		$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
		$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

		//set auto page breaks
		$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

		//set image scale factor
		$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

		// add a page
		$pdf->AddPage();
		
		$pdf->SetFont('freesans', '', 8);
		
		// create some HTML content
		$Model = JModel::getInstance($model_name, 'PimModel');
		$html = $Model->PDFReport();

		// output the HTML content
		$pdf->writeHTML($html, true, true, false, false, '');
		$pdf->lastPage();
		
		$filename = $model_name . '_' . date('d-m-Y') . '.pdf';
		$pdf->Output($filename, 'I');
		
		exit;
	}
	
	static function formatExcel($model_name, $_header='', $_detail_header='') {
		$config = self::getAllPimConfig();
		
		$logo = !empty($config['logo'])?$config['logo']:'';
		$header = !empty($config['company_name'])?$config['company_name'].' - '.$config['address']:$_header;
		$detail_header = !empty($config['website'])?$config['website'].' - '.$config['email'].' - '.$config['phone'].' - '.$config['fax']:$_detail_header;	
		
		// Create new PHPExcel object
		$objPHPExcel = new PHPExcel();
		
		// Set document properties
		$objPHPExcel->getProperties()->setCreator("Pim")
							 ->setLastModifiedBy("Pim")
							 ->setTitle($model_name)
							 ->setSubject("MS EXCEL")
							 ->setDescription($model_name);
		
		// Set active sheet
		$objPHPExcel->setActiveSheetIndex(0);
		
		// Add a drawing to the worksheet
		if (!empty($logo)) {
			$objDrawing = new PHPExcel_Worksheet_Drawing();
			$objDrawing->setPath($logo, false);
			$objDrawing->setCoordinates('A1');
			$objDrawing->setHeight(60); 
			$objDrawing->setWorksheet($objPHPExcel->getActiveSheet());
		}
		
		// Title detail
		$objPHPExcel->getActiveSheet()->SetCellValue('B1', $header);
		$objPHPExcel->getActiveSheet()->SetCellValue('B2', $detail_header);
		$objPHPExcel->getActiveSheet()->getStyle('B1:B2')->getFont()->setBold(true);
		
		// Rename worksheet
		$objPHPExcel->getActiveSheet()->setTitle($model_name);
		
		// Get data
		$Model = JModel::getInstance($model_name, 'PimModel');
		$objPHPExcel = $Model->ExcelReport($objPHPExcel);
		
		// Auto resize width of column and format cell
		self::formatCell($objPHPExcel->getActiveSheet(), 'A');

		$filename = $model_name.'_' . date('d-m-Y') . '.xls';
		
		// Redirect output to a client’s web browser (Excel5)
		header('Content-Type: application/vnd.ms-excel');
		header('Content-Disposition: attachment;filename="'.$filename.'"');
		header('Cache-Control: max-age=0');
		
		$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
		$objWriter->save('php://output');
		
        exit;
	}
	
	static function formatCell($sheet, $fromCol, $toCol='') {
        if (empty($toCol) ) {//not defined the last column, set it the max one
            $toCol = $sheet->getColumnDimension($sheet->getHighestColumn())->getColumnIndex();
        }
        for($i = $fromCol; $i <= $toCol; $i++) {
        	// Resize width
            $sheet->getColumnDimension($i)->setAutoSize(true);
            
            // Format title
            $sheet->getStyle($i.self::ROW_START_EXPORT_EXCEL)->getFont()->getColor()->setARGB(PHPExcel_Style_Color::COLOR_BLUE);
            $sheet->getStyle($i.self::ROW_START_EXPORT_EXCEL)->getFont()->setBold(true);
            $sheet->getStyle($i.self::ROW_START_EXPORT_EXCEL)->getFont()->setSize(14);
            $sheet->getStyle($i.self::ROW_START_EXPORT_EXCEL)->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
            $sheet->getStyle($i.self::ROW_START_EXPORT_EXCEL)->getFill()->getStartColor()->setARGB(PHPExcel_Style_Color::COLOR_YELLOW);
        }
        
        $styleArray = array(
        	'borders' => array( 
        		'allborders' => array( 'style' => PHPExcel_Style_Border::BORDER_THIN, ), 
        	),
        	'alignment' => array( 
        		'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER, 
        	),
        );
        $highestRow = $sheet->getRowDimension($sheet->getHighestRow())->getRowIndex();
        $sheet->getStyle($fromCol.self::ROW_START_EXPORT_EXCEL.':'.$toCol.$highestRow)->applyFromArray($styleArray);
        
        $sheet->calculateColumnWidths();
    }
}
